package com.lottery.ruok.lottrey.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.util.TimeUtils;
import android.view.View;
import android.view.ViewStub;
import android.widget.AdapterView;
import android.widget.ListView;

import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.adapter.ChargeRecordAdapter;
import com.lottery.ruok.lottrey.dialog.FiltrateDialog;
import com.lottery.ruok.lottrey.eventbusObject.FilterGetLogs;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.RechargeLogRequest;
import com.lottery.ruok.lottrey.retrofitModule.request.WithdrawalsLogRequest;
import com.lottery.ruok.lottrey.retrofitModule.response.RechargeLogResponse;
import com.lottery.ruok.lottrey.userInfo.UserInfo;
import com.lottery.ruok.lottrey.utils.TimeUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;

import ui.NavigateBar;
/*
* 充值记录 && 提现记录
* */
public class ChargeRecordActivity extends BaseActivity {

    @BindView(R.id.navigateBar)
    NavigateBar navigateBar;
    @BindView(R.id.listview)
    ListView listview;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;
    private View emptyLayout;

    private final int pageNum = 20;
    private boolean isInitData = true;

    private void setEmtpyView(){
        if (emptyLayout == null) {
            ViewStub stub = findViewById(R.id.no_net_viewstub);
            View view = stub.inflate();
            emptyLayout = view.findViewById(R.id.no_net_view);
            emptyLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    isInitData = true;
                    getList(filterStartTime, filterEndTime, filterTypes, 0);
                }
            });
        }
    }

    private RechargeLogResponse rechargeLogResponse;

    private ChargeRecordAdapter myAdapter;

    private int type;
    private int mPage = 0;

    private String filterStartTime;
    private String filterEndTime;
    private String filterTypes;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_charge_record);
        ButterKnife.bind(this);

        EventBus.getDefault().register(this);

        init();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void startFilter(FilterGetLogs filterGetLogs){
        mPage = 0;
        filterStartTime = filterGetLogs.getStart_time();
        filterEndTime = filterGetLogs.getEnd_time();
        filterTypes = filterGetLogs.getTypes();
        isInitData = false;
        getList(filterStartTime, filterEndTime, filterTypes, mPage);
    }

    private void getList(String time_start, String time_end, String types, final int page){
        if(type == 1) {
            RetrofitBase.getRetrofit().create(RechargeLogRequest.class).getResult(UserInfo.getToken(), time_start, time_end, types, page * 20, pageNum)
                    .compose(RxHelper.<RechargeLogResponse>handleResult())
                    .subscribe(new RxSubscribe<RechargeLogResponse>(this) {
                        @Override
                        protected void _onNext(RechargeLogResponse g) {
                            if(g.getList() != null && g.getList().size() < pageNum){
                                mRefreshLayout.setEnableLoadMore(false);
                            }else{
                                mRefreshLayout.setEnableLoadMore(true);
                            }
                            if(page == 0) {
                                rechargeLogResponse = g;
                                mRefreshLayout.finishRefresh();
                            } else {
                                rechargeLogResponse.getList().addAll(g.getList());
                                mRefreshLayout.finishLoadMore();
                            }

                            mPage = page;

                            if(myAdapter != null){
                                myAdapter.setDatas(rechargeLogResponse);
                                myAdapter.notifyDataSetChanged();
                            } else {
                                myAdapter = new ChargeRecordAdapter(rechargeLogResponse, ChargeRecordActivity.this);
                                listview.setAdapter(myAdapter);
                            }

                            if(rechargeLogResponse.getList().size() == 0) {
                                setEmtpyView();
                            } else {
                                if(emptyLayout != null){
                                    emptyLayout.setVisibility(View.GONE);
                                }
                            }
                        }

                        @Override
                        public void onError(Throwable e) {
                            super.onError(e);

                            if(page == 0) {
                                mRefreshLayout.finishRefresh();
                            } else {
                                mRefreshLayout.finishLoadMore();
                            }

                            if(rechargeLogResponse == null || rechargeLogResponse.getList().size() == 0) {
                                setEmtpyView();
                            }
                        }

                        @Override
                        protected boolean showDialog() {
                            if(isInitData){
                                return true;
                            }
                            return false;
                        }
                    });
        } else if(type == 2){
            navigateBar.setCenterTitle("提现记录");
            RetrofitBase.getRetrofit().create(WithdrawalsLogRequest.class).getResult(UserInfo.getToken(), time_start, time_end, types, page * 20, pageNum)
                    .compose(RxHelper.<RechargeLogResponse>handleResult())
                    .subscribe(new RxSubscribe<RechargeLogResponse>(this) {
                        @Override
                        protected void _onNext(RechargeLogResponse g) {
                            if(g.getList() != null && g.getList().size() < pageNum){
                                mRefreshLayout.setEnableLoadMore(false);
                            }else{
                                mRefreshLayout.setEnableLoadMore(true);
                            }
                            if(page == 0) {
                                rechargeLogResponse = g;
                                mRefreshLayout.finishRefresh();
                            } else {
                                rechargeLogResponse.getList().addAll(g.getList());
                                mRefreshLayout.finishLoadMore();
                            }

                            mPage = page;

                            if(myAdapter != null){
                                myAdapter.setDatas(rechargeLogResponse);
                                myAdapter.notifyDataSetChanged();
                            } else {
                                myAdapter = new ChargeRecordAdapter(rechargeLogResponse, ChargeRecordActivity.this);
                                listview.setAdapter(myAdapter);
                            }

                            if(rechargeLogResponse.getList().size() == 0) {
                                setEmtpyView();
                            } else {
                                if(emptyLayout != null){
                                    emptyLayout.setVisibility(View.GONE);
                                }
                            }
                        }

                        @Override
                        public void onError(Throwable e) {
                            super.onError(e);

                            if(page == 0) {
                                mRefreshLayout.finishRefresh();
                            } else {
                                mRefreshLayout.finishLoadMore();
                            }

                            if(rechargeLogResponse == null || rechargeLogResponse.getList().size() == 0) {
                                setEmtpyView();
                            }
                        }

                        @Override
                        protected boolean showDialog() {
                            if(isInitData){
                                return true;
                            }
                            return false;
                        }
                    });
        }
    }

    private void init() {
        type = getIntent().getIntExtra("type", 0);

        navigateBar.setOnOperateClickListener(new NavigateBar.OnOperateClickListener() {
            @Override
            public void onOperateClick(View view) {
                FiltrateDialog filtrateDialog = new FiltrateDialog();
                Bundle bundle = new Bundle();
                if(type == 1){
                    bundle.putInt("type", 2);
                } else if(type == 2){
                    bundle.putInt("type", 3);
                }
                bundle.putString("types", filterTypes);
                bundle.putString("startTime",filterStartTime);
                bundle.putString("endTime",filterEndTime);
                filtrateDialog.setArguments(bundle);
                FragmentTransaction fts = getSupportFragmentManager().beginTransaction();
                fts.setCustomAnimations(R.anim.anim_enter_from_bottom, R.anim.anim_exit_from_bottom, R.anim.anim_enter_from_bottom, R.anim.anim_exit_from_bottom);
                fts.replace(android.R.id.content, filtrateDialog);
                fts.addToBackStack("account");
                fts.commitAllowingStateLoss();
            }
        });
       /* String startTime=  TimeUtil.getStartTime();
        String endTime= TimeUtil.getEndTime();
        getList(startTime, endTime, null, mPage);*/
        isInitData = true;
        getList(null, null, null, mPage);

        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if(rechargeLogResponse.getList().size() > 0) {
                    Intent intent = new Intent(ChargeRecordActivity.this, ChargeDetailActivity.class);
                    intent.putExtra("deal_no", rechargeLogResponse.getList().get(i).getOrdernum());
                    intent.putExtra("deal_time", rechargeLogResponse.getList().get(i).getSubmit_time());
                    intent.putExtra("deal_model", rechargeLogResponse.getList().get(i).getType3());
                    intent.putExtra("condition", rechargeLogResponse.getList().get(i).getType4_desc());
                    intent.putExtra("money", rechargeLogResponse.getList().get(i).getAmount());
                    intent.putExtra("discounts", rechargeLogResponse.getList().get(i).getOffer1());
                    intent.putExtra("offer2", rechargeLogResponse.getList().get(i).getOffer2());
                    intent.putExtra("remark", rechargeLogResponse.getList().get(i).getRemark());
                    intent.putExtra("type", type);
                    startActivity(intent);
                }
            }
        });

      /*  // 设置下拉刷新和上拉加载更多的风格     参数1：应用程序上下文，参数2：是否具有上拉加载更多功能
        BGARefreshViewHolder refreshViewHolder = new BGANormalRefreshViewHolder(this, true);
        // 设置下拉刷新和上拉加载更多的风格
        swipeRefreshLayout.setRefreshViewHolder(refreshViewHolder);

        swipeRefreshLayout.setDelegate(new BGARefreshLayout.BGARefreshLayoutDelegate() {
            @Override
            public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
                getList(filterStartTime, filterEndTime, filterTypes, mPage + 1);
                return true;
            }

            @Override
            public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
                mPage = 0;
                getList(filterStartTime, filterEndTime, filterTypes, mPage);
            }
        });*/
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                mRefreshLayout.setEnableRefresh(true);//启用刷新
                mPage = 0;
                isInitData = false;
                getList(filterStartTime, filterEndTime, filterTypes, mPage);
            }
        });
        mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                mRefreshLayout.setEnableLoadMore(true);//启用加载
                isInitData = false;
                getList(filterStartTime, filterEndTime, filterTypes, mPage + 1);
            }
        });
    }
}
